import React, {useEffect, useState} from 'react';
import {Resizable as Resz} from 're-resizable';

import './header.css';

const enable = {
  top:         false,
  right:       true,
  bottom:      false,
  left:        false,
  topRight:    false,
  bottomRight: false,
  bottomLeft:  false,
  topLeft:     false
}

const HeaderCol = ({colKey, width: initWidth, setColWidth=e=>e, children}) =>{
  
  const [width, setHeaderWidth] = useState(initWidth);

  const [isShowingColKey, toggleShowingColKey] = useState(false);

  useEffect(() => {
    setHeaderWidth(initWidth);
  }, [initWidth])


  return <Resz
    defaultSize={{width}}
    size={{width}}
    className='list-header-col'
    onResizeStop={(e, direction, ref, delta) => {
      const {width} = getComputedStyle(ref);
      setHeaderWidth(width + delta.width);
      setColWidth(colKey, width);
    }}
    onClick={() => {
      toggleShowingColKey(!isShowingColKey);
    }}
    enable={enable}
  ><div className="list-header-col-inner">{children}{isShowingColKey && ` - [${colKey}]`}</div>
  </Resz>;

}


export default ({setColWidth=e=>e, cols}) => {

  const colsElem = Object.entries(cols).map(([key, {width, desc}]) => {
    const colProps = {
      key,
      colKey:key,
      children: desc,
      width,
      setColWidth
    }
    return <HeaderCol {...colProps} />
  })

  return <div className="list-header">{colsElem}</div>
}
